package net.halflite.mzkr.action.regist;

import java.util.Map;

import javax.annotation.Resource;

import net.halflite.mzkr.annotation.SessionRequired;
import net.halflite.mzkr.form.regist.ReissuePasswordForm;
import net.halflite.mzkr.service.RegistedUserService;
import net.halflite.mzkr.type.TempUserType;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.seasar.struts.annotation.ActionForm;
import org.seasar.struts.annotation.Execute;
import org.seasar.struts.enums.SaveType;

/** パスワード再登録のアクションクラス */
public class PasswordAction {
	@Resource
	private Map<String, Object> sessionScope;

	@Resource
	private RegistedUserService registedUserService;
	
	@ActionForm
	@Resource(name = "regist_reissuePasswordForm")
	private ReissuePasswordForm form;

	/** メールに記載された本登録URL */
	@Execute(urlPattern = "{hash}", validate = "validate", input = "fault.jsp")
    public String index() {
		sessionScope.put("hashKey", form.hash);
        return "input?redirect=true";
    }

	/** 入力 */
    @SessionRequired(redirect = "/", keys = "hashKey")
    @Execute(validator = false)
    public String input() {
        return "input.jsp";
    }

    /** 登録 */
    @SessionRequired(redirect = "/", keys = "hashKey")
    @Execute(validate = "validateHash", saveErrors = SaveType.SESSION, input = "input?redirect=true")
    public String post() {
    	registedUserService.reissuePassword(form);
        return "success?redirect=true";
    }
	
	/** 完了画面 */
	@Execute(validator = false, removeActionForm = true)
    public String success() {
		sessionScope.remove("hashKey");
        return "success.jsp";
    }

	public ActionMessages validate() {
		return registedUserService.validateHash(form.hash, TempUserType.PASSWORD);
	}
	
	public ActionMessages validateHash() {
		ActionMessages result = new ActionMessages();
		String hash = (String) sessionScope.get("hashKey");
		if (!StringUtils.equals(form.hash, hash)) result.add("hash", new ActionMessage("errors.invalid.hash"));
		return result;
	}
}
